package com.mornd.gulimall.order.receiver;

import com.mornd.gulimall.apis.seckill.to.SeckillOrderTo;
import com.mornd.gulimall.order.service.IOrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author: mornd
 * @dateTime: 2023/8/30 - 9:33
 */

@Slf4j
@Component
public class OrderSeckillReceiver {
    @Resource
    private IOrderService orderService;

    /**
     * 处理用户秒杀成功后的业务
     */
    @RabbitListener(queues = "order.seckill.queue")
    public void handleOrderSeckill(Message message,
                                   SeckillOrderTo seckillOrderTo,
                                   Channel channel) throws IOException {
        log.info("收到秒杀单，{}", seckillOrderTo.getOrderSn());
        try {
            orderService.createSeckillOrder(seckillOrderTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error(e.getMessage());
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
        log.info("秒杀单处理结束");
    }
}
